package com.fr.similarity.string;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;

/**
 * @author furong
 * @version 创建时间：2016-4-1 上午10:37:29
 */
public class StringSimilarity {
	public static float similarity(List<String> a, List<String> b){
		if (CollectionUtils.isEmpty(a) || CollectionUtils.isEmpty(b)){
			return 0 ;
		}
		float rs = 0;
		int lenA = a.size();
		int lenB = b.size();
		float rate = 1.0f;
		if (lenA < 3 && lenB < 3){
			rate -= 0.3;
		}

		List<Integer> vectorA = new ArrayList<>();
		List<Integer> vectorB = new ArrayList<>();
		for(int i = 0; i< lenA; i++){
			for(int j = 0; j < lenB; j++){
				if (a.get(i).equalsIgnoreCase(b.get(j))){
					vectorA.add(lenA - i);
					vectorB.add(lenB - j);
				}
			}
		}
		int sumXY = 0;
		int sumXX = sum(lenA);
//		int sumXX = 0;
		int sumYY = sum(lenB);
		if (CollectionUtils.isNotEmpty(vectorA)){			
			for(int i = 0; i < vectorA.size(); i++){
				int x = vectorA.get(i), y= vectorB.get(i);
				sumXY += x * y;
//				sumXX += x * x;
			}
			rs = (float) (rate * sumXY / Math.sqrt(sumXX) / Math.sqrt(sumYY));
		}
		if (lenA > 6 && lenB > 8){
			rs = (float) Math.sqrt(rs);
		}
		return rs;
	}

	public static int sum (int n){
		int sum = 0;
		for(int i = 1; i <= n; i++){
			sum += (i * i);
		}
		return sum;
	}

}
